<?php

namespace app\controllers;

use app\components\Common;
use app\models\Task;
use app\models\TaskItem;
use app\models\Video;
use app\models\Website;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\ContactForm;
use Exception;
//require_once(__DIR__ . '/../vendor/phpoffice/phpexcel/Classes/PHPExcel.php') ;

class SiteController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout'],
                'rules' => [
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    public function actionIndex()
    {
        if(!empty($_POST['data'])){
            try{
                $data_arr = explode("\r\n",trim($_POST['data']));
                $line_data = array();
                foreach ($data_arr as $item) {
                    $line_data[] = explode("\t",trim($item));
                }
                $title_data = array_shift($line_data);
                $project_person = array();

                $project = array();
                if(!empty($line_data)){
                    $data_cols = count($line_data[0]);
                    foreach ($line_data as $v) {
                        $cur_projects = explode("、",$v[2]);
                        if(!empty($cur_projects)){
                            foreach ($cur_projects as $v2) {
                                $v2 = trim($v2);
                                if(!isset($project_person[$v2])){
                                    $project_person[$v2] = 0;
                                }
                                $mod = 0 ;
                                for($i = 3;$i< $data_cols;$i++){
                                    $cur_fee = floor($v[$i]/count($cur_projects));
                                    $mod =$v[$i]%count($cur_projects);
                                    if(isset($project[$i][$v2])){
                                        $project[$i][$v2] += $cur_fee;
                                    }else{
                                        $project[$i][$v2] = $cur_fee;
                                    }

                                    if($v2 == $cur_projects[count($cur_projects)-1]){
                                        //加上余数
                                        $project[$i][$v2] += $mod;
                                    }
                                }
                                $project_person[$v2] += round(1/count($cur_projects));
                            }

                        }else{
                            throw new Exception("亲人，第".$v[0]."行没有项目！", 500);
                        }
                    }
                    //导出excel

                    //发起下载
                    Header("Content-type: application/octet-stream");
                    Header("Accept-Ranges: bytes");
                    Header("Content-Disposition: attachment; filename=结果.csv");

                    $project_names = array_keys($project_person);
                    $title = '"费用","'.implode('","',$project_names).'","总额"';
                    echo iconv("UTF-8", "GB2312", $title) . "\n";

                    //分段请求数据

                    //扫描包含的商品，计数并聚合
                    $data = array();
                    foreach ($project as $k => $row) {
                        $line = array();
                        $line[] = iconv("UTF-8", "GB2312", $title_data[$k]);
                        $total = 0;
                        foreach ($project_names as $project_name) {
                            $line[] = $row[$project_name];
                            $total+=$row[$project_name];
                        }
                        $line[] = $total;
                        $data[] = $line;
                    }
                    $data[] = array();

                    $line = array();
                    $line[] = iconv("UTF-8", "GB2312", '总人数');
                    $total = 0;
                    foreach ($project_names as $project_name) {
                        $line[] = $project_person[$project_name];
                        $total+=$row[$project_name];
                    }
                    $line[] = $total;
                    $data[] = $line;

                    foreach ($data as $row) {
                        echo '"' . implode('","', array_values($row)) . "\"\n";
                    }
                    exit;

                }else{
                    throw new Exception("亲人，数据不能为空啊！", 500);
                }
            }catch (Exception $e){
                Common::setShowMsg(true,$e->getMessage());
            }

//            var_dump($title_data ,$line_data);exit;

        }

        return $this->render('index');
    }

    public function actionLogin()
    {
        if (!\Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        }
        return $this->render('login', [
            'model' => $model,
        ]);
    }

    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }

    public function actionContact()
    {
        $model = new ContactForm();
        if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail'])) {
            Yii::$app->session->setFlash('contactFormSubmitted');

            return $this->refresh();
        }
        return $this->render('contact', [
            'model' => $model,
        ]);
    }

    public function actionAbout()
    {
        return $this->render('about');
    }
}
